<template>
  <el-card shadow="hover">
    <template #header>
      <div class="card-header">
        <el-button @click="handleAddTrademark" class="button" type="primary" :icon="Plus">添加</el-button>
      </div>
    </template>
    <!-- 品牌列表 -->
    <el-table :data="trademarkList" border style="width: 100%" v-loading="loading" element-loading-text="Loading..."
      element-loading-svg-view-box="-10, -10, 50, 50" :element-loading-spinner="svg">
      <el-table-column label="序号" width="120" v-slot="{ $index }">
        {{ $index + 1 }}
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="品牌LOGO" v-slot="{ row }">
        <el-image style="width: 100px; height: 100px" :src="row.logoUrl" fit="contain" />
      </el-table-column>
      <el-table-column label="操作" v-slot="{ row }">
        <el-button @click="handleEdit(row)" type="warning" :icon="Edit" size="small" title="编辑" />
        <el-button @click="handleDelete(row)" type="danger" :icon="Delete" size="small" title="删除" />
      </el-table-column>
    </el-table>
    <!-- 表格分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[3, 5, 10, 20, 50]"
        :small="false" :disabled="false" :background="false" layout="prev, pager, next,jumper,->,sizes,total,"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 修改品牌 -->
    <el-dialog v-model="editDialogVisible" title="修改品牌">
      <el-form ref="formRef" :rules="rules" :model="form">
        <el-form-item prop="tmName" label="品牌名称" :label-width="100">
          <el-input v-model="form.tmName" autocomplete="off" style="max-width: 400px;width:80%; max-width: 200px;" />
        </el-form-item>
        <el-form-item required label="品牌LOGO" :label-width="100">
          <!-- 上传LOGO -->
          <el-upload class="avatar-uploader" :action="`${uploadUrl}/admin/product/upload`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png 文件最大不能超过 2M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reqGetBaseTrademark, reqUpdateTrademart, reqDeleteTrademark, reqAddTrademark } from '@/api/product/trademark'
import type { TrademarkItem, TrademarkList } from '@/api/product/model/trademark'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'
export default {
  name: 'trademark',
}
</script>
<script setup lang="ts">
const page = ref(1)
const limit = ref(3)
const total = ref(0)
const trademarkList = ref<TrademarkList>([])
const editDialogVisible = ref(false)
const form = ref<TrademarkItem>({ id: 0, tmName: '', logoUrl: '' })
const formRef = ref<FormInstance>()
const submitType = ref('add')
const loading = ref(false)
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '品牌名称不能为空！' }
  ],
  logoUrl: [
    { required: true, message: '图片不能为空！' }
  ]
})
// 根据不同环境使用不同的 url
const uploadUrl = import.meta.env.VITE_API_URL

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `

// 获取品牌数据
const GetBaseTrademark = async () => {
  // 开启加载框
  loading.value = true
  const res = await reqGetBaseTrademark(page.value, limit.value)
  // console.log(res)
  trademarkList.value = res.records
  total.value = res.total
  // limit.value = res.size
  // page.value = res.current

  // 关闭加载框
  loading.value = false
}
// 每页数据条数改变后
const handleSizeChange = (val: number) => {
  limit.value = val
  page.value = 1 // 页码重置为1
  // 重新获取trademark 数据
  GetBaseTrademark()

}
// 改变页码后
const handleCurrentChange = (val: number) => {
  page.value = val
  // 重新获取trademark 数据
  GetBaseTrademark()
}

// 编辑
const handleEdit = (row: TrademarkItem) => {
  // 提交类型为 更新
  submitType.value = 'update'

  editDialogVisible.value = true
  // 防止引用行内的，备份一份
  form.value = ({ ...row })
}
// 删除
const handleDelete = (row: TrademarkItem) => {
  ElMessageBox.confirm(
    `确定要删除 ${row.tmName} 吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 删除品牌
      await reqDeleteTrademark(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功！',
      })
      // 删除成功后重新获取数据
      GetBaseTrademark()
    }, () => {
      ElMessage({
        type: 'info',
        message: '已取消删除！',
      })
    }).catch(() => { })
}

// 上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // form.value.logoUrl = URL.createObjectURL(uploadFile.raw!)
  // 上传成功后收到返回的 url ，显示图像 
  form.value.logoUrl = response.data
}

// 上传之前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 提交修改
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      // 更新
      if (submitType.value == 'update') {
        await reqUpdateTrademart(form.value)
        ElMessage({
          type: 'success',
          message: '修改品牌成功！'
        })
      } else {
        // 添加
        await reqAddTrademark(form.value)
        ElMessage({
          type: 'success',
          message: '添加品牌成功！'
        })
      }

      // 关闭对话框
      editDialogVisible.value = false

      // 修改/添加成功后重新获取数据
      GetBaseTrademark()
    } else {
      console.log('error submit!')
      return false
    }
  })
}

// 点击添加按钮
const handleAddTrademark = () => {
  // 清空表单
  form.value = { tmName: '', logoUrl: '' }

  editDialogVisible.value = true

  // 提交类型为 添加
  submitType.value = 'add'

  setTimeout(() => {
    formRef.value?.clearValidate()
  }, 0);
  // nextTick(()=>{
  //   formRef.value?.clearValidate()
  // })
}

onMounted(() => {
  // 获取品牌数据
  GetBaseTrademark()
})
</script>

<style scoped>
.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>